<template>
  <div style="min-height: 100vh; background: #f5f5f5; padding: 20px;">
    <div style="position: fixed; top: 20px; right: 20px; z-index: 100;">
      <el-button-group>
        <el-button type="primary" @click="handleBack">
          <el-icon><Back /></el-icon> 返回
        </el-button>
        <el-button type="primary" @click="handlePrint">
          <el-icon><Printer /></el-icon> 打印
        </el-button>
        <el-button type="primary" @click="handleDownload">
          <el-icon><Download /></el-icon> 下载
        </el-button>
      </el-button-group>
    </div>

    <div style="max-width: 210mm; margin: 0 auto; background: white; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); padding: 20mm;">
      <div>
        <!-- 文档头部 -->
        <div style="margin-bottom: 40px;">
          <div style="text-align: right; font-size: 14px; line-height: 1.8;">
            <div>方案编号：{{ protocolInfo.protocolNumber }}</div>
            <div>版本号：{{ protocolInfo.version }}</div>
            <div>版本日期：{{ protocolInfo.updateTime }}</div>
          </div>
        </div>

        <!-- 文档内容 -->
        <template v-if="sections.length">
          <div>
            <div v-for="section in sections" :key="section.id" style="margin-bottom: 40px;">
              <h2 style="font-size: 16px; font-weight: bold; margin-bottom: 24px;">{{ section.title }}</h2>
              
              <div v-for="form in section.forms" :key="form.id" style="margin-bottom: 32px;">
                <h3 style="font-size: 15px; font-weight: bold; margin-bottom: 20px;">
                  {{ form.title }}
                  <span style="font-size: 14px; color: #666; margin-left: 8px;">({{ form.id }})</span>
                </h3>
                
                <template v-if="form.fields.length">
                  <div v-for="field in form.fields" :key="field.id" style="margin-bottom: 24px;">
                    <!-- 日期时间组 -->
                    <template v-if="field.type === 'dateTimeGroup'">
                      <p :style="{ lineHeight: 2, marginBottom: '16px', textAlign: field.value?.alignment || 'left' }">
                        本人于
                        <span style="display: inline-block; min-width: 60px; text-align: center;">
                          <span style="border-bottom: 1px solid #000;">{{ formatNumber(field.value?.year) }}</span>
                        </span>
                        年
                        <span style="display: inline-block; min-width: 40px; text-align: center;">
                          <span style="border-bottom: 1px solid #000;">{{ formatNumber(field.value?.month, 2) }}</span>
                        </span>
                        月
                        <span style="display: inline-block; min-width: 40px; text-align: center;">
                          <span style="border-bottom: 1px solid #000;">{{ formatNumber(field.value?.day, 2) }}</span>
                        </span>
                        日
                        <span style="display: inline-block; min-width: 40px; text-align: center;">
                          <span style="border-bottom: 1px solid #000;">{{ formatNumber(field.value?.hour, 2) }}</span>
                        </span>
                        时
                        <span style="display: inline-block; min-width: 40px; text-align: center;">
                          <span style="border-bottom: 1px solid #000;">{{ formatNumber(field.value?.minute, 2) }}</span>
                        </span>
                        分{{ field.suffix }}
                      </p>
                    </template>

                    <!-- 单选带输入 -->
                    <template v-if="field.type === 'radioWithInput'">
                      <div :style="{ lineHeight: 2, marginBottom: '16px', textAlign: field.value?.alignment || 'left' }">
                        <div style="margin-bottom: 8px;">{{ field.value?.label }}</div>
                        <div style="margin: 8px 0;">
                          <span 
                            v-for="option in field.value?.options"
                            :key="option.value"
                            style="margin-right: 32px; display: inline-block;"
                          >
                            <span style="font-family: sans-serif; margin-right: 4px; font-size: 16px;">{{ field.value?.selected === option.value ? '●' : '○' }}</span>
                            {{ option.label }}
                            <template v-if="option.showInput && field.value?.selected === option.value">
                              <span style="margin: 0 4px;">{{ option.inputLabel }}</span>
                              <span style="display: inline-block; min-width: 120px;">
                                <span style="display: block; border-bottom: 1px solid #000; min-height: 21px;">{{ field.value?.inputValue || '' }}</span>
                              </span>
                            </template>
                          </span>
                        </div>
                      </div>
                    </template>





                    <!-- 标准表格 -->
                    <template v-if="field.type === 'criteriaTable'">
                      <div :style="{ margin: '24px 0', textAlign: field.value?.alignment || 'left' }">
                        <div style="text-align: center; font-weight: bold; margin-bottom: 16px;">{{ field.value?.title }}</div>
                        <table style="width: 100%; border-collapse: collapse;">
                          <thead>
                            <tr>
                              <th v-for="col in field.value?.columns" :key="col.id" 
                                  style="border: 1px solid #000; padding: 8px; text-align: center; font-size: 14px; background: #f8f8f8; font-weight: bold;"
                                  :style="{ width: col.width }">
                                {{ col.title }}
                              </th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="row in field.value?.rows" :key="row.id">
                              <td v-for="col in field.value?.columns" :key="col.id" 
                                  style="border: 1px solid #000; padding: 8px; text-align: center; font-size: 14px;">
                                <!-- 序号 -->
                                <template v-if="col.type === 'number'">
                                  {{ row[col.id] }}
                                </template>
                                
                                <!-- 文本/多行文本 -->
                                <template v-else-if="col.type === 'text' || col.type === 'textarea'">
                                  {{ row[col.id] || '' }}
                                </template>
                                
                                <!-- 单选 -->
                                <template v-else-if="col.type === 'radio'">
                                  <div style="display: flex; justify-content: center; gap: 16px;">
                                    <span v-for="opt in col.options" :key="opt.value" style="white-space: nowrap;">
                                      <span style="font-family: sans-serif; margin-right: 4px;">{{ row[col.id] === opt.value ? '☑' : '☐' }}</span>
                                      {{ opt.label }}
                                    </span>
                                  </div>
                                </template>
                                
                                <!-- 复选框 -->
                                <template v-else-if="col.type === 'checkbox'">
                                  <div style="display: flex; justify-content: center; gap: 16px;">
                                    <span v-for="opt in col.options" :key="opt.value" style="white-space: nowrap;">
                                      <span style="font-family: sans-serif; margin-right: 4px;">
                                        {{ row[col.id]?.includes(opt.value) ? '☑' : '☐' }}
                                      </span>
                                      {{ opt.label }}
                                    </span>
                                  </div>
                                </template>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                        <div v-if="field.value?.note" style="margin-top: 8px; font-size: 12px; color: #666; font-style: italic;">{{ field.value.note }}</div>
                      </div>
                    </template>
                  </div>
                </template>
                <div v-else style="padding: 24px; text-align: center; color: #909399; font-size: 14px; background: #f5f7fa; border-radius: 4px;">
                  暂无字段配置
                </div>
              </div>
            </div>
          </div>
        </template>
        <div v-else style="padding: 24px; text-align: center; color: #909399; font-size: 14px; background: #f5f7fa; border-radius: 4px;">
          暂无表单数据
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Printer, Download, Back } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 加载表单列表
const sections = ref([])

// 方案信息
const protocolInfo = ref({
  protocolNumber: 'XXXX',
  version: '1.0',
  updateTime: '2025 年 04 月 28 日'
})

// 格式化数字
const formatNumber = (num, width = 0) => {
  if (!num && num !== 0) return '_'.repeat(width || 1)
  const str = num.toString()
  return width ? str.padStart(width, '0') : str
}

// 打印
const handlePrint = () => {
  window.print()
}

// 下载
const handleDownload = () => {
  ElMessage.success('开始下载文档')
}

// 返回表单列表
const handleBack = () => {
  router.push('/form')
}

// 加载方案信息
const loadProtocolInfo = () => {
  try {
    const savedProtocolInfo = localStorage.getItem('protocolInfo')
    if (savedProtocolInfo) {
      const data = JSON.parse(savedProtocolInfo)
      protocolInfo.value = data
    }
  } catch (error) {
    console.error('Load protocol info error:', error)
  }
}

// 加载表单数据
const loadForms = () => {
  try {
    // 1. 加载表单列表结构
    const formListStr = localStorage.getItem('formList')
    if (!formListStr) {
      ElMessage.warning('未找到表单列表数据')
      return
    }
    
    const formList = JSON.parse(formListStr)
    
    // 2. 转换为预览所需的结构
    sections.value = formList
      .filter(item => item.type === 'section')
      .map(section => ({
        id: section.id,
        title: section.name,
        forms: section.children
          .filter(form => form.type === 'form')
          .map(form => ({
            id: form.id,
            title: form.name,
            fields: form.config?.fields || [] // 直接从表单配置中获取字段
          }))
      }))

    // 3. 如果表单配置不在 form.config 中，尝试从 localStorage 加载
    sections.value.forEach(section => {
      section.forms.forEach(form => {
        if (!form.fields || !form.fields.length) {
          const formConfig = localStorage.getItem(`form_${form.id}_config`)
          if (formConfig) {
            try {
              const config = JSON.parse(formConfig)
              form.fields = config.fields || []
            } catch (error) {
              console.error(`Load form ${form.id} config error:`, error)
            }
          }
        }
      })
    })

    // 4. 如果没有数据，显示提示
    if (!sections.value.length) {
      ElMessage.warning('没有可预览的表单数据')
      router.push('/form')
    }
  } catch (error) {
    console.error('Load forms error:', error)
    ElMessage.error('加载表单失败')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadProtocolInfo()
  loadForms()
})
</script>

<style>
@media print {
  .preview-page {
    padding: 0 !important;
    background: white !important;
  }

  .preview-toolbar {
    display: none !important;
  }

  .document-container {
    box-shadow: none !important;
    padding: 0 !important;
    max-width: none !important;
  }

  @page {
    size: A4;
    margin: 20mm;
  }
}
</style> 